<template>
  <div style="border: 1px solid #ccc; z-index: 999999">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="props.mode" />
    <Editor ref="shallowRef" :style="{ height: `${props.height}px`, overFlow: 'hidden' }" v-model="valueHtml" :defaultConfig="editorConfig" :mode="props.mode" @onCreated="handleCreated" />
  </div>
</template>

<script lang="ts" setup>
  import { shallowRef, ref, onMounted, onBeforeUnmount, computed } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { IEditorConfig, DomEditor } from '@wangeditor/editor'
  import '@wangeditor/editor/dist/css/style.css'
  import { OSSUpload } from '@/utils/ossUpload'
  type InsertFnType = (url: string, alt?: string, href?: string) => void
  const props = defineProps({
    modelValue: {
      type: String,
      default: '',
    },
    height: {
      type: Number,
      default: 500,
    },
    // 去除菜单栏某些选项
    excludeKeys: {
      type: Array,
      default: [],
    },
    // 类型
    mode: {
      type: String,
      default: 'default',
    },
  })
  const emits = defineEmits(['update:modelValue'])

  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef()
  const toolbarConfig: any = {
    excludeKeys: props.excludeKeys,
  }
  const editorConfig: any = {
    MENU_CONF: {},
  }
  // const mode = ref('default')
  // 内容 HTML
  const valueHtml = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })

  const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
  }

  // 上传图片
  editorConfig.MENU_CONF['uploadImage'] = {
    // server: '/api/upload',
    // 自定义上传
    async customUpload(file: File, insertFn: InsertFnType) {
      const res: any = await OSSUpload(file)
      insertFn(res.url)
    },
  }

  // 上传视频
  editorConfig.MENU_CONF['uploadVideo'] = {
    // 自定义上传
    async customUpload(file: File, insertFn: InsertFnType) {
      const res: any = await OSSUpload(file)
      insertFn(res.url)
    },
  }

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
</script>

<style lang="less" scoped></style>
